const path = require('path');
const Koa = require('koa');
const send = require('koa-send');

const getFilePaths = require('./utils/getFilePaths');

const app = new Koa();

const isDev = process.env.NODE_ENV === 'development';
// 处理静态资源文件
// const staticRouter = require('./routes/static');

// 处理服务器端渲染
const pageRouter = isDev ? require('./routes/dev-ssr') : require('./routes/ssr');

app.use(async (ctx, next) => {
  try {
    console.log(`request with path : ${ctx.path}`);
    await next();
  } catch (error) {
    console.log(error);
    if (isDev) {
      ctx.body = error.message;
    } else {
      ctx.body = 'please try again later!'
    }
  }
});

// 预加载dist静态资源文件
let pathArr = [];
getFilePaths(pathArr, path.join(__dirname, '../dist'));

// 发送静态资源文件
app.use(async (ctx, next)=>{

  if (!isDev){
    /**
     * 处理静态资源文件,
     * 不能采用for循环，否则 await next会多次调用导致异常。
     */
    if(pathArr.indexOf(ctx.path) !== -1){
      await send(ctx, pathArr[pathArr.indexOf(ctx.path)], {root: path.join(__dirname, '../dist')})
    }else if (ctx.path === '/favicon.ico'){
      await send(ctx, '/favicon.ico', {root: path.join(__dirname, '../')})
    } else {
      await next();
    }
  } else {
    if (ctx.path === '/favicon.ico'){
      await send(ctx, '/favicon.ico', {root: path.join(__dirname, '../')})
    } else {
      await next();
    }
  }
});

const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || '3333';

// app.use(staticRouter.routes()).use(staticRouter.allowedMethods);
app.use(pageRouter.routes()).use(pageRouter.allowedMethods);

app.listen(PORT, HOST, ()=>{
  console.log(`server is listening on ${HOST}:${PORT}`);
});